package com.task;


import com.alibaba.fastjson.JSONObject;
import com.pojo.MovieList;
import com.service.DyService;
import com.util.HardUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.util.*;

@Service
public class TimeTaskXiajiaDyService {

    @Autowired
    private DyService dyService;


    @Value("${server.url}")
    private String server;


    @Value("${dy.home}")
    private String home;

    @Autowired
    private RestTemplate restTemplate;


    /**
     * 下架
     */
    @Scheduled(cron = "29 0/10 * * * ?")
    public synchronized void removeDy() {
        List<MovieList> remoteList = null;
        String mainboardID = HardUtil.getMainBorId();
        String url = server + "/api/v1/getMovieBySite?mainboardID={1}";
        if (server.startsWith("http://172.") || server.startsWith("http://192.") || server.startsWith("http://10.")) {
            //url = server + "/api/v1/getAllDy?mainboardID={1}";
        }
        String response = restTemplate.getForObject(url, String.class, mainboardID);
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject != null) {
            int code = jsonObject.getInteger("code");
            if (code != 200) {
                System.out.println(jsonObject.getString("msg"));
                return;
            }

            //获取远程节目列表
            remoteList = jsonObject.parseArray(jsonObject.getString("data"), MovieList.class);
            //获取本地节目列表
            List<MovieList> localList = dyService.list();


            //比较
            List<MovieList> addList = new ArrayList(); //要新增的电影
            List<MovieList> removeList = new ArrayList();//要删除的电影
            if (localList != null && remoteList != null) {

                removeList = removeAll(localList, remoteList);
            }
            //删除下架电影
            if (removeList != null) {
                for (MovieList m : removeList) {
                    m.setIs_it_on_the_shelf(0);
                    dyService.updateById(m);
                }
            }
        }
    }


    private List<MovieList> removeAll(List<MovieList> src, List<MovieList> target) {
        LinkedList<MovieList> result = new LinkedList<MovieList>(src); //大集合用linkedlist
        HashSet<MovieList> targetHash = new HashSet<MovieList>(target); //小集合用hashset
        Iterator<MovieList> iter = result.iterator(); //采用Iterator迭代器进行数据的操作

        while (iter.hasNext()) {
            MovieList m = iter.next();
            if (targetHash.contains(m)) {
                iter.remove();
            }
        }
        return result;
    }
}
